import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:geomancy/models/base_model.dart';
import 'package:geomancy/models/common_model.dart';
import 'package:geomancy/providers/user_provider.dart';
import 'package:geomancy/tools/http.dart';
import 'package:geomancy/tools/utils.dart';
import 'package:provider/provider.dart';

class UserAPI {
  ///查询用户信息
  static Future<User?> getUserInfo(BuildContext context, int id) async {
    try {
      final data = await Fetch.request(Method.GET, '/user/getById/$id', context: context);
      final result = CommonModel.fromJson(json.decode(data.data));
      if (result.code == 200) {
        final User u = User.fromJson(result.data);
        return u;
      }
      return null;
    } catch(e) {
      return null;
    }
  }
  
  
  ///更新用户信息（注册步骤）
  static Future<bool> update({required BuildContext context, required UserUpdateAPIData user}) async {
    try {
      final userProvider = context.read<UserProvider>();
      final data = await Fetch.request(Method.POST, '/user/update', params: user.toJson(), context: context);
      final result = CommonModel.fromJson(json.decode(data.data));
      if (result.code == 200) {
        final User? u = userProvider.getUserInfo;
        if (u != null) {
          /// 合并数据更新回目标对象 u ;
          Utils.mergeObjects<User, UserUpdateAPIData>(u, user);
          userProvider.saveUserInfo(u);
        }
        return true;
      } else {
        EasyLoading.showToast(result.message);
      }
      return false;
    } catch(e) {
      return false;
    }
  }

  ///修改用户信息（个人资料-编辑）
  static Future<bool> edit({required BuildContext context, required UserEditAPIData user}) async {
    try {
      final userProvider = context.read<UserProvider>();
      final data = await Fetch.request(Method.POST, '/user/modifyUserInfo', params: user.toJson(), context: context);
      final result = CommonModel.fromJson(json.decode(data.data));
      if (result.code == 200) {
        final User? u = userProvider.getUserInfo;
        if (u != null) {
          /// 合并数据更新回目标对象 u ;
          Utils.mergeObjects<User, UserEditAPIData>(u, user);
          userProvider.saveUserInfo(u);
        }
        return true;
      } else {
        EasyLoading.showToast(result.message);
      }
      return false;
    } catch(e) {
      return false;
    }
  }

  ///注销用户
  static Future<bool> deleteUser(BuildContext context) async {
    try {
      final data = await Fetch.request(Method.GET, '/user/deleteUser', context: context);
      print('data==$data');
      final result = CommonModel.fromJson(json.decode(data.data));
      if (result.code == 200) {
        return true;
      }
      return false;
    } catch(e) {
      print('e==$e');
      return false;
    }
  }
}